/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <Handler.h>
#include <Message.h>
#include <MessagePool.h>

static Message* newMessage() {
    Message* msg = malloc(sizeof(Message));
    if (!msg) {
        return NULL;
    }
    memset(msg, 0, sizeof(Message));
    return msg;
}

Message* messageObtain(Handler* handler, uint32_t what, void* obj) {
    Message* msg = messagePoolObtain();
    if (!msg) {
        msg = newMessage();
    }

    msg->target = handler;
    msg->what = what;
    msg->obj = obj;

    return msg;
}


boolean messageSendToTarget(Message* msg) {
    if (!msg || !msg->target) {
        return FALSE;
    }

    return handlerSendMessage(msg->target, msg);
}


void messageRecycleUnchecked(Message* msg) {
    // Mark the message as in use while it remains in the recycled object pool.
    // Clear out all other details.
    if (msg) {
        msg->what = 0;
        msg->arg1 = 0;
        msg->arg2 = 0;
        msg->when = 0;
        msg->target = NULL;
        if (msg->obj) {
            free(msg->obj);
            msg->obj = NULL;
        }

        messagePoolAdd(msg);
    }
}

